<template>
  <div class="page-content">
    <art-table-bar
      :showTop="false"
      @search="search"
      @reset="resetForm(searchFormRef)"
      @changeColumn="changeColumn"
      @changeSearchWrap="changeSearchWrap"
      :columns="columns"
    >
      <template #top>
        <el-form :model="searchForm" ref="searchFormRef" label-width="82px">
          <el-row :gutter="20">
            <ArtFormInput label="昵称" prop="name" v-model="searchForm.usrName" />
            <ArtFormInput label="手机号" prop="phone" v-model="searchForm.usrPhone" />
            <ArtFormSelect label="性别" prop="sex" v-model="searchForm.usrSex" :options="sexOptions" />
          </el-row>
        </el-form>
      </template>
      <template #bottom>
        <el-button @click="showDialog('add')" v-ripple>添加员工</el-button>
      </template>
    </art-table-bar>
    <el-table
      :data="tableData" 
      v-loading="loading"
      style="width: 100%"
      :fit="true"
      :height="isShowSearchWrap ? 'calc(100vh - 345px)' : 'calc(100vh - 283px)'"
    >
      <template #default>
        <el-table-column
          label="用户名"
          prop="avatar"
          #default="scope"
          min-width="200"
          v-if="columns[0].show"
        >
          <div class="user" style="display: flex; align-items: center">
            <img v-if="scope.row.parsedImage.length" 
              :src="scope.row.parsedImage[0].path" 
              class="avatar"
            />
            <img v-else
              :src="user"
              class="avatar" 
            />
            <div>
              <p class="user-name">{{ scope.row.usrName }}</p>
              <p class="email">{{ scope.row.usrNo }}</p>
            </div>
          </div>
        </el-table-column>
        <el-table-column label="手机号" prop="usrPhone" min-width="120" v-if="columns[1].show" />
        <el-table-column label="性别" prop="usrSex" min-width="80" #default="scope" v-if="columns[2].show">
          {{ scope.row.usrSex == 1 ? usrSexStatus.MALE : usrSexStatus.FEMALE }}
        </el-table-column>
        <el-table-column label="所在部门" prop="deptNames" min-width="120" v-if="columns[3].show">
          <template #default="scope">
            {{scope.row.deptNames}}
          </template>
        </el-table-column>
        <el-table-column
          label="人员状态"
          prop="employmentStatus"
          min-width="100"
          v-if="columns[4].show"
        >
          <template #default="scope">
            <el-tag  v-if="scope.row.employmentStatus != ''" :type="getTagType(scope.row.employmentStatus)">
              {{ buildTagText(scope.row.employmentStatus)}}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="入职时间" prop="entryTime" min-width="120" sortable v-if="columns[5].show" >
          <template #default="scope">
            {{scope.row.entryTime ? useDateFormat(scope.row.entryTime, 'YYYY-MM-DD') : ''}}
          </template>
        </el-table-column>
        <el-table-column label="工龄开始时间" prop="workStartDate" min-width="120" v-if="columns[6].show">
          <template #default="scope">
            {{scope.row.workStartDate ? useDateFormat(scope.row.workStartDate, 'YYYY-MM-DD') : ''}}
          </template>
        </el-table-column>
        <!-- <el-table-column label="职务职责" prop="jobResponsibilities" min-width="120" v-if="columns[7].show" />
        <el-table-column label="工作地点" prop="workPlace" min-width="120" v-if="columns[8].show" /> -->
        <el-table-column label="学历" prop="education" min-width="100" v-if="columns[7].show" />
        <el-table-column label="婚否" prop="maritalStatus" min-width="80" v-if="columns[8].show">
          <template #default="scope">
            {{ scope.row.maritalStatus == '1' ? whetherOrNot.CORRECT : scope.row.maritalStatus == '2' ? whetherOrNot.DENY : '' }}
          </template>
        </el-table-column>
        <el-table-column label="出生地" prop="birthPlace" min-width="120" v-if="columns[9].show" />
        <el-table-column label="国籍" prop="nationality" min-width="100" v-if="columns[10].show" />
        <el-table-column label="民族" prop="ethnicity" min-width="100" v-if="columns[11].show" />
        <el-table-column label="籍贯" prop="hometown" min-width="100" v-if="columns[12].show" />
        <el-table-column label="政治面貌" prop="politicalStatus" min-width="100" v-if="columns[13].show" />
        <el-table-column label="宗教信仰" prop="religion" min-width="100" v-if="columns[14].show" />
        <el-table-column label="户籍性质" prop="residencyNature" min-width="100" v-if="columns[15].show" />
        <el-table-column label="是否入党" prop="isPartyMember" min-width="100" v-if="columns[16].show">
          <template #default="scope">
            {{ scope.row.isPartyMember == '1' ? whetherOrNot.CORRECT : scope.row.isPartyMember == '2' ? whetherOrNot.DENY : '' }}
          </template>
        </el-table-column>
        <el-table-column label="是否退役军人" prop="isVeteran" min-width="120" v-if="columns[17].show">
          <template #default="scope">
            {{ scope.row.isVeteran == '1' ? whetherOrNot.CORRECT : scope.row.isVeteran == '2' ? whetherOrNot.DENY : '' }}
          </template>
        </el-table-column>
        <el-table-column label="参军时间" prop="enlistmentDate" min-width="120" v-if="columns[18].show">
          <template #default="scope">
            {{scope.row.enlistmentDate ? useDateFormat(scope.row.enlistmentDate, 'YYYY-MM-DD') : ''}}
          </template>
        </el-table-column>
        <el-table-column label="退役时间" prop="dischargeDate" min-width="120" v-if="columns[19].show">
          <template #default="scope">
            {{scope.row.dischargeDate ? useDateFormat(scope.row.dischargeDate, 'YYYY-MM-DD') : ''}}
          </template>
        </el-table-column>
        <el-table-column label="创建日期" prop="createTime" min-width="120" sortable v-if="columns[20].show" >
          <template #default="scope">
            {{scope.row.createTime ? useDateFormat(scope.row.createTime, 'YYYY-MM-DD') : ''}}
          </template>
        </el-table-column>
        <el-table-column 
          label="操作" 
          min-width="100"
          fixed="right"
          class="operation-column"
        >
          <template #default="scope">
            <!-- <ArtButtonTable type="edit" @click="showDialog('edit', scope.row)" /> -->
            <el-button type="primary" size="small" link @click="showDialog('edit', scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <!-- 分页器 -->
    <div class="flex justify-center mt-5">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div> 
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加员工' : '编辑员工'"
      width="70%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="头像" prop="usrHeadUrl">
              <div class="w-full">
                <MyUpload
                  :file-list="fileList"
                  :limit="1"
                  :width="'120px'"
                  :height="'120px'"
                  @deleteFile="deleteFile"
                  @uploadFileSuccess="success"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账号" prop="usrNo">
              <el-input v-model="formData.usrNo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="usrName">
              <el-input v-model="formData.usrName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="usrPhone">
              <el-input v-model="formData.usrPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="usrSex">
              <el-select v-model="formData.usrSex">
                <el-option
                  v-for="(value, key) in usrSexMaps"
                  :key="key"
                  :label="value"
                  :value="key + 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所在部门" prop="deptIds">
            <el-cascader
              v-model="deptIdsLIst"
              :options="computedDeptOptions"
              :props="deptIdsprops"
              clearable
              placeholder="请选择部门"
              :show-all-levels="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="人员状态" prop="employmentStatus">
          <el-select v-model="formData.employmentStatus">
            <el-option
              v-for="(value, key) in employmentStatusMaps"
              :key="key"
              :label="value.label"
              :value="key + 1"
            />
          </el-select>
        </el-form-item>
        </el-col>
       </el-row>
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入职时间" prop="entryTime">
          <el-date-picker
            v-model="formData.entryTime"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYYMMDD"
          />
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工龄开始时间" prop="workStartDate">
          <el-date-picker
            v-model="formData.workStartDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYYMMDD"
          />
        </el-form-item>
        </el-col>
       </el-row>
       <!-- <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职务职责" prop="jobResponsibilities">
          <el-input v-model="formData.jobResponsibilities" />
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作地点" prop="workPlace">
          <el-input v-model="formData.workPlace" />
        </el-form-item>
        </el-col>
       </el-row> -->
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学历" prop="education">
            <el-input v-model="formData.education" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="婚否" prop="maritalStatus">
          <el-select v-model="formData.maritalStatus">
            <el-option
              v-for="(value, key) in whetherOrNotMaps"
              :key="key"
              :label="value"
              :value="key + 1"
            />
          </el-select>
        </el-form-item>
        </el-col>
       </el-row>
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="出生地" prop="birthPlace">
            <el-input v-model="formData.birthPlace" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="国籍" prop="nationality">
          <el-input v-model="formData.nationality" />
        </el-form-item>
        </el-col>
       </el-row>
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="民族" prop="ethnicity">
          <el-input v-model="formData.ethnicity" />
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="籍贯" prop="hometown">
          <el-input v-model="formData.hometown" />
        </el-form-item>
        </el-col>
       </el-row>
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="政治面貌" prop="politicalStatus">
          <el-input v-model="formData.politicalStatus" />
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="宗教信仰" prop="religion">
          <el-input v-model="formData.religion" />
        </el-form-item>
        </el-col>
       </el-row>
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="户籍性质" prop="residencyNature">
          <el-input v-model="formData.residencyNature" />
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否入党" prop="isPartyMember">
          <el-select v-model="formData.isPartyMember">
            <el-option
              v-for="(value, key) in whetherOrNotMaps"
              :key="key"
              :label="value"
              :value="key + 1"
            />
          </el-select>
        </el-form-item>
        </el-col>
       </el-row>
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否退役军人" prop="isVeteran">
          <el-select v-model="formData.isVeteran">
            <el-option
              v-for="(value, key) in whetherOrNotMaps"
              :key="key"
              :label="value"
              :value="key + 1"
            />
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参军时间" prop="enlistmentDate">
          <el-date-picker
            v-model="formData.enlistmentDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYYMMDD"
          />
        </el-form-item>
        </el-col>
       </el-row>
       <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="退役时间" prop="dischargeDate">
          <el-date-picker
            v-model="formData.dischargeDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYYMMDD"
          />
        </el-form-item>
        </el-col>
       </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetBindForm">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { useDateFormat } from '@vueuse/core'
  import { 
    sysUserPageUserUsingPost,
    sysUserSaveUserUsingPost,
    sysUserUpdateUserUsingPost,
    sysUserGetUserByIdUsingPost 
  } from '@/api/4a/yonghu'
  import { sysDeptListDeptUsingPost } from '@/api/4a/bumen'
  import type { SysDeptduixiang, bumenrenyuanxinxi } from '@/api/4a/types'
  import { usrSexStatus,whetherOrNot } from '@/types/user'
  import user from '@/assets/img/user.png'
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)


  const formData = reactive({
    usrHeadUrlList: '',
    usrHeadUrl: '',
    usrNo: '',
    usrName: '',
    usrPhone: '',
    usrSex: '',
    deptId: '',
    employmentStatus: '',
    entryTime: '',
    usrType: 0,
    workStartDate:'',
    jobResponsibilities:'',
    workPlace:'',
    education:'',
    maritalStatus:'',
    birthPlace:'',
    nationality:'',
    ethnicity:'',
    hometown:'',
    politicalStatus:'',
    religion:'',
    residencyNature:'',
    isPartyMember:'',
    isVeteran:'',
    enlistmentDate:'',
    dischargeDate:'',
    deptIds:[]
  })
  // 分页参数
  const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })

  const sexOptions = [
    {
      value: '1',
      label: '男'
    },
    {
      value: '2',
      label: '女'
    }
  ]

  const deptIdsLIst = ref([])

  
  const deptIdsprops = {
  multiple: true,
  checkStrictly: true,
  }

  const columns = reactive([
    { name: '用户名', show: true },
    { name: '手机号', show: true },
    { name: '性别', show: true },
    { name: '所在部门', show: true },
    { name: '人员状态', show: true },
    { name: '入职时间', show: true },
    { name: '工龄开始时间', show: true },
    // { name: '职务职责', show: true },
    // { name: '工作地点', show: true },
    { name: '学历', show: true },
    { name: '婚否', show: true },
    { name: '出生地', show: true },
    { name: '国籍', show: true },
    { name: '民族', show: true },
    { name: '籍贯', show: true },
    { name: '政治面貌', show: true },
    { name: '宗教信仰', show: true },
    { name: '户籍性质', show: true },
    { name: '是否入党', show: true },
    { name: '是否退役军人', show: true },
    { name: '参军时间', show: true },
    { name: '退役时间', show: true },
    { name: '创建日期', show: true }
  ])

  const searchFormRef = ref<FormInstance>()
  const searchForm = reactive({
    usrName: '',
    usrPhone: '',
    usrSex: '',
  })

  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    searchForm.usrName = ''
    searchForm.usrPhone = ''
    searchForm.usrSex = ''
    getTableData()
  }

  const tableData = ref<any[]>([])

  const isShowSearchWrap = ref(false)

  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    getTableData()
  }
  
  // 页码改变
  const handleCurrentChange = (val: number) => {
    pagination.current = val
    getTableData()
  }

  // 每页条数改变
  const handleSizeChange = (val: number) => {
    pagination.size = val
    pagination.current = 1
    getTableData()
  }

  const showDialog =  (type: string, row?: any) => {
    formRef.value?.resetFields();
    dialogVisible.value = true
    dialogType.value = type
    deptIdsLIst.value = []
    getDeptTreeData() // 获取部门数据
    if (type === 'edit' && row) {
      // 获取用户详情
      getDetails(row.id)
     
    }
  }

  const deleteUser = () => {
    ElMessageBox.confirm('确定要注销该用户吗？', '注销用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      ElMessage.success('注销成功')
    })
  }

  const search = () => {
    pagination.current = 1
    getTableData()
  }

  const changeColumn = (list: any) => {
    columns.values = list
  }

  const changeSearchWrap = (val: any) => {
    isShowSearchWrap.value = val
  }


  const getTagType = (status: string) => {
    switch (status) {
      case '1':
        return 'success'
      case '2':
        return 'info'
      case '3':
        return 'warning'
      case '4':
        return 'danger'
      default:
        return 'info'
    }
  }

  const buildTagText = (status: string) => {
    let text = ''
    if (status == '1') {
      text = '在职'
    } else if (status == '2') {
      text = '离职'
    } 
    return text
  }

  const rules = reactive<FormRules>({
    usrNo: [
      { required: true, message: '请输入账号', trigger: 'blur' },
      { pattern: /^[^\u4e00-\u9fa5]+$/, message: '账号不能包含中文', trigger: 'blur' }
    ],
    usrName: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
    ],
    usrPhone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    usrSex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    usrHeadUrl: [{ required: true, message: '请上传头像', trigger: 'change' }]
  })

  const formRef = ref<FormInstance>()

  // 人员状态
  const employmentStatusMaps = [
    {
      value: 1,
      label: '在职'
    },
    {
      value: 2,
      label: ' 离职'
    }
  ]

  // 性别
  const usrSexMaps = Object.keys(usrSexStatus).map(
    (key) => usrSexStatus[key as keyof typeof usrSexStatus]
  )

  // 是否
  const whetherOrNotMaps = Object.keys(whetherOrNot).map(
    (key) => whetherOrNot[key as keyof typeof whetherOrNot]
  )

  const handleSubmit = async () => {
    if(formData.usrType == null){
      formData.usrType = 0
    }
    // if(formData.usrHeadUrlList && formData.usrHeadUrlList != '[]' && formData.usrHeadUrlList != '[null]'){
      // const list = JSON.parse(formData.usrHeadUrlList)
      // if(list.length > 0){
      // formData.usrHeadUrl = list[0].path
    // }
    // }else{
    //   formData.usrHeadUrl='0'
    // }
    if (deptIdsLIst.value.length > 0) {
      formData.deptIds = []
      // 遍历每个选中的部门数组，取最后一个值
      deptIdsLIst.value.forEach(deptArray => {
        formData.deptIds.push(deptArray[deptArray.length - 1])
      })
    }
    if (!formRef.value) return
      await formRef.value.validate(async(valid) => {
      if (valid) {
        if(dialogType.value === 'add'){
          const response = await sysUserSaveUserUsingPost({
            body: formData
            })
            
            if (response.data) {
              ElMessage.success('添加成功')
              dialogVisible.value = false
              getTableData() // 刷新列表
            } else {
              ElMessage.error(response.msg)
            }
          }else{
            const response = await sysUserUpdateUserUsingPost({
              body: formData
              })
              
              if (response.data) {
                ElMessage.success('修改成功')
                dialogVisible.value = false
                getTableData() // 刷新列表
              } else {
                ElMessage.error(response.msg)
              }
          }
        }
    })
  }
  // 重置绑定表单
  const resetBindForm = () => {
    dialogVisible.value = false
    
  }

  // 获取列表数据
  const getTableData = async () => {
    try {
      loading.value = true
      const res = await sysUserPageUserUsingPost({
         body: {
          ...searchForm,
          current: pagination.current,
          size: pagination.size
        }
      })
      if (res.code == 0) {
        // 处理每个部门的管理人员显示和部门名称
        tableData.value = (res.data?.list || []).map(item => ({
          ...item,
          parsedImage: (() => {
            try {
              const images = JSON.parse(item.usrHeadUrl || '[]')
              return Array.isArray(images) ? images : []
            } catch (e) {
              return []
            }
          })(),
          deptNames: item.sysDeptUserVoList?.map((dept: bumenrenyuanxinxi) => dept.deptName || '').filter(Boolean).join(', ') || ''
        }))
        pagination.total = res.data?.total || 0
      }
    } catch (error) {
      ElMessage.error('获取员工列表失败')
    } finally {
      loading.value = false
    }
  }

  // 头像
  const fileList = computed({
    get() {
      return JSON.parse(formData.usrHeadUrl || '[]')
    },
    set(value) {
      formData.usrHeadUrl = value
    }
  })

  const success = (a:any) => {
    fileList.value.push(a.data)
    fileList.value = JSON.stringify(fileList.value)
  }

  const deleteFile = (params:any) => {
    fileList.value = JSON.stringify(fileList.value.filter((item:any) => item.path !== params.path))
  }

  // 获取详情
  const getDetails = async(id:any) =>{
  const response = await sysUserGetUserByIdUsingPost({
        body: {
          id: id
        }
      })
      if (response.code === 0 && response.data) {
        Object.assign(formData,response.data)
          if(response.data.usrHeadUrl == '0'){
             formData.usrHeadUrl = ''
          }
          deptIdsLIst.value = []
          if (response.data.sysDeptUserVoList?.length) {
            response.data.sysDeptUserVoList.forEach((dept: any) => {
              if (dept.id) {
                deptIdsLIst.value.push(dept.deptId)
              }
            })
          }
          
      }
  }
   
   // 部门数据
   const deptOptions = ref<SysDeptduixiang[]>([])

   // 获取部门树形数据
   const getDeptTreeData = async () => {
     try {
       const response = await sysDeptListDeptUsingPost({
         body: {}
       })
       if (response.data) {
         deptOptions.value = response.data
       }
     } catch (error) {
       ElMessage.error('获取部门列表失败')
     }
   }  

   // 递归构建部门选项
   const buildDeptOptions = (depts: any) => {
     return depts.map((dept:any) => ({
       value: dept.id,
       label: dept.deptName,
       children: dept.sysDeptVoList ? buildDeptOptions(dept.sysDeptVoList) : []
     }))
   }

   // 计算部门选项
   const computedDeptOptions = computed(() => {
     return buildDeptOptions(deptOptions.value)
   })

   // 初始化获取数据
   onMounted(() => {
    getTableData()
    
  })
</script>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    height: 100%;

    .user {
      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  .el-date-editor.el-input{
    width: 100%;
  }
</style>
